package com.geek.factory.service.configq;

import com.geek.factory.entity.Product;
import com.geek.factory.mapper.ProductMapper;
import com.geek.factory.mapper.ProductionPlanMapper;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.ibatis.session.SqlSessionFactory;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Slf4j
public class ProductionPlanCompleteJob   implements Job {

    /*@Autowired  // 直接注入 Mapper
    private ProductionPlanMapper planMapper;

    @Override
    public void execute(JobExecutionContext context) {
        JobDataMap dataMap = context.getMergedJobDataMap();
        Long planId = dataMap.getLong("planId");
        Long productId = dataMap.getLong("productId");
        String completeTimeStr = dataMap.getString("completeTime");

        SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) dataMap.get("sqlSessionFactory");

        try (var session = sqlSessionFactory.openSession(true)) {
            ProductionPlanMapper planMapper = session.getMapper(ProductionPlanMapper.class);
            ProductMapper productMapper = session.getMapper(ProductMapper.class);

            // 1. 更新生产计划状态
            planMapper.updateStatusToCompleted(planId);

            // 2. 更新原产品完成时间
            productMapper.updateCompleteTime(productId, completeTimeStr);

            // 3. 查询原产品信息
            Product oldProduct = productMapper.selectById(productId);
            if (oldProduct != null) {
                // 4. 构造新产品对象（复制原信息）
                Product newProduct = new Product();
                newProduct.setName(oldProduct.getName());
                newProduct.setCode(oldProduct.getCode() + "-C"); // 可加后缀防止重复
                newProduct.setModel(oldProduct.getModel());
                newProduct.setCategory(oldProduct.getCategory());
                newProduct.setPrice(oldProduct.getPrice());
                newProduct.setDescription("由计划 " + planId + " 生成");
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
                newProduct.setCompleteTime(LocalDateTime.parse(completeTimeStr, formatter));
                newProduct.setStatus("in_stock"); // 初始状态为“已入库”或其他

                // 5. 插入新产品
                productMapper.insertNewProduct(newProduct);
            }

            log.info("计划完成：planId={}, productId={}，插入新产品记录成功", planId, productId);
        } catch (Exception e) {
            log.error("定时任务执行失败：", e);
        }
    }
*/

    @Override
    public void execute(JobExecutionContext context) {
        JobDataMap dataMap = context.getMergedJobDataMap();
        Long planId = dataMap.getLong("planId");
        Long productId = dataMap.getLong("productId");
        String completeTimeStr = dataMap.getString("completeTime");

        SqlSessionFactory sqlSessionFactory = (SqlSessionFactory) dataMap.get("sqlSessionFactory");

        try (var session = sqlSessionFactory.openSession(true)) {
            ProductionPlanMapper planMapper = session.getMapper(ProductionPlanMapper.class);
            ProductMapper productMapper = session.getMapper(ProductMapper.class);

            // 1. 更新生产计划状态为已完成（2）
            planMapper.updatePlanStatus(planId, "2");

            // 2. 更新原产品的完成时间
            productMapper.updateCompleteTime(productId, completeTimeStr);

            // 3. 查询原产品信息
            Product oldProduct = productMapper.selectById(productId);
            if (oldProduct != null) {
                // 4. 复制原产品信息，生成新记录
                Product newProduct = new Product();
                newProduct.setName(oldProduct.getName());
                newProduct.setCode(oldProduct.getCode() + "-C");
                newProduct.setModel(oldProduct.getModel());
                newProduct.setCategory(oldProduct.getCategory());
                newProduct.setPrice(oldProduct.getPrice());
                newProduct.setDescription("由计划 " + planId + " 生成");


                newProduct.setCompleteTime(Timestamp.valueOf(completeTimeStr).toLocalDateTime());


                // 设置状态为已完成（1）
//                newProduct.setStatus("1");

                String statusStr = "1";  // 假设这是来自数据库或 API 的 String 值
                Integer status = Integer.valueOf(statusStr);  // 转为 Integer
                newProduct.setStatus(status);

                // 5. 插入新产品
                productMapper.insertNewProduct(newProduct);
            }

            log.info("计划完成：planId={}, productId={}，插入新产品记录成功", planId, productId);
        } catch (Exception e) {
            log.error("定时任务执行失败：", e);
        }
    }




}
